package GUIuse;

import GUIuse.mainuse.OrderManagementSystem;
import common.Customer;
import common.Order;
import common.Product;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class OrderPanel extends JPanel {
    private OrderManagementSystem parent;
    private JTable orderTable;
    private DefaultTableModel tableModel;
    private JButton addButton, viewButton, deleteButton, refreshButton;
    
    public OrderPanel(OrderManagementSystem parent) {
        this.parent = parent;
        initialize();
    }
    
    private void initialize() {
        setLayout(new BorderLayout());
        
        // 创建表格模型和表格
        String[] columnNames = {"订单编号", "下单日期", "下单客户编号", "总金额", "订单项数量"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        orderTable = new JTable(tableModel);
        orderTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(orderTable);
        add(scrollPane, BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        
        addButton = new JButton("添加订单");
        viewButton = new JButton("查看订单");
        deleteButton = new JButton("删除订单");
        refreshButton = new JButton("刷新");
        
        buttonPanel.add(addButton);
        buttonPanel.add(viewButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);
        
        add(buttonPanel, BorderLayout.NORTH);
        
        // 添加按钮事件监听
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddOrderDialog();
            }
        });
        
        viewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showOrderDetailDialog();
            }
        });
        
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteSelectedOrder();
            }
        });
        
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable();
            }
        });
        
        // 初始加载数据
        refreshTable();
    }
    
    // 刷新表格数据
    public void refreshTable() {
        tableModel.setRowCount(0); // 清空表格
        List<Order> orders = parent.getOrders();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        for (Order order : orders) {
            Object[] rowData = {
                order.getOrderNumber(),
                dateFormat.format(order.getOrderDate()),
                order.getCustomerId(),
                order.getTotalAmount(),
                order.getOrderItems().size()
            };
            tableModel.addRow(rowData);
        }
    }
    
    // 生成订单编号
    private String generateOrderNumber() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(new Date());
        Random random = new Random();
        int randomNum = 1000 + random.nextInt(9000); // 生成1000-9999之间的随机数
        return "ORD-" + dateStr + "-" + randomNum;
    }
    
    // 显示添加订单对话框
    private void showAddOrderDialog() {
        // 检查是否有可用商品
        if (parent.getProducts().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请先添加商品信息", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        JDialog dialog = new JDialog((Frame) null, "添加订单", true);
        dialog.setSize(800, 500);
        dialog.setLocationRelativeTo(null);
        dialog.setLayout(new BorderLayout());
        
        // 创建订单信息面板
        JPanel orderInfoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        orderInfoPanel.setBorder(BorderFactory.createTitledBorder("订单信息"));
        
        JLabel orderNumberLabel = new JLabel("订单编号:");
        JTextField orderNumberField = new JTextField(20);
        orderNumberField.setText(generateOrderNumber());
        orderNumberField.setEditable(false);
        
        JLabel orderDateLabel = new JLabel("下单日期:");
        JTextField orderDateField = new JTextField(20);
        orderDateField.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        orderDateField.setEditable(false);
        
        JLabel customerIdLabel = new JLabel("客户编号:");
        JComboBox<Integer> customerIdComboBox = new JComboBox<>();
        customerIdComboBox.setPreferredSize(new Dimension(150, 25));
        
        // 添加客户编号到下拉框
        for (Customer customer : parent.getCustomers()) {
            customerIdComboBox.addItem(customer.getId());
        }
        
        orderInfoPanel.add(orderNumberLabel);
        orderInfoPanel.add(orderNumberField);
        orderInfoPanel.add(orderDateLabel);
        orderInfoPanel.add(orderDateField);
        orderInfoPanel.add(customerIdLabel);
        orderInfoPanel.add(customerIdComboBox);
        
        // 创建商品选择和数量面板
        JPanel productPanel = new JPanel(new BorderLayout());
        productPanel.setBorder(BorderFactory.createTitledBorder("选择商品"));
        
        // 商品列表和数量输入
        DefaultListModel<Product> productListModel = new DefaultListModel<>();
        for (Product product : parent.getProducts()) {
            productListModel.addElement(product);
        }
        JList<Product> productList = new JList<>(productListModel);
        productList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        productList.setCellRenderer(new ProductListRenderer());
        
        JPanel selectionPanel = new JPanel(new BorderLayout());
        selectionPanel.add(new JScrollPane(productList), BorderLayout.CENTER);
        
        JPanel quantityPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel quantityLabel = new JLabel("数量:");
        JTextField quantityField = new JTextField(10);
        JButton addItemButton = new JButton("添加到订单");
        
        quantityPanel.add(quantityLabel);
        quantityPanel.add(quantityField);
        quantityPanel.add(addItemButton);
        
        selectionPanel.add(quantityPanel, BorderLayout.SOUTH);
        
        // 创建订单商品表格
        String[] columnNames = {"商品编号", "商品名称", "单价", "数量", "小计"};
        DefaultTableModel orderItemsTableModel = new DefaultTableModel(columnNames, 0);
        JTable orderItemsTable = new JTable(orderItemsTableModel);
        orderItemsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        JPanel orderItemsPanel = new JPanel(new BorderLayout());
        orderItemsPanel.setBorder(BorderFactory.createTitledBorder("订单商品"));
        orderItemsPanel.add(new JScrollPane(orderItemsTable), BorderLayout.CENTER);
        
        // 总金额显示
        JPanel totalPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JLabel totalLabel = new JLabel("订单总金额: ");
        JTextField totalField = new JTextField(15);
        totalField.setEditable(false);
        totalField.setBackground(Color.LIGHT_GRAY);
        totalField.setText("0.00");
        
        totalPanel.add(totalLabel);
        totalPanel.add(totalField);
        
        orderItemsPanel.add(totalPanel, BorderLayout.SOUTH);
        
        // 分割面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, selectionPanel, orderItemsPanel);
        splitPane.setDividerLocation(300);
        
        productPanel.add(splitPane, BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton saveButton = new JButton("保存订单");
        JButton cancelButton = new JButton("取消");
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        // 添加到对话框
        dialog.add(orderInfoPanel, BorderLayout.NORTH);
        dialog.add(productPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加订单项按钮事件
        addItemButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Product selectedProduct = productList.getSelectedValue();
                if (selectedProduct == null) {
                    JOptionPane.showMessageDialog(dialog, "请选择要添加的商品", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                try {
                    int quantity = Integer.parseInt(quantityField.getText());
                    if (quantity <= 0) {
                        JOptionPane.showMessageDialog(dialog, "请输入有效的数量", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    
                    // 检查商品是否已在订单中
                    boolean found = false;
                    for (int i = 0; i < orderItemsTableModel.getRowCount(); i++) {
                        int productId = (int) orderItemsTableModel.getValueAt(i, 0);
                        if (productId == selectedProduct.getId()) {
                            // 更新数量
                            int currentQuantity = (int) orderItemsTableModel.getValueAt(i, 3);
                            orderItemsTableModel.setValueAt(currentQuantity + quantity, i, 3);
                            orderItemsTableModel.setValueAt((double) selectedProduct.getUnitPrice() * (currentQuantity + quantity), i, 4);
                            found = true;
                            break;
                        }
                    }
                    
                    // 如果商品不在订单中，添加新行
                    if (!found) {
                        Object[] rowData = {
                            selectedProduct.getId(),
                            selectedProduct.getName(),
                            selectedProduct.getUnitPrice(),
                            quantity,
                            selectedProduct.getUnitPrice() * quantity
                        };
                        orderItemsTableModel.addRow(rowData);
                    }
                    
                    // 更新总金额
                    updateTotalAmount(orderItemsTableModel, totalField);
                    
                    // 清空数量输入框
                    quantityField.setText("");
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(dialog, "请输入有效的数量", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        // 保存订单按钮事件
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (orderItemsTableModel.getRowCount() == 0) {
                    JOptionPane.showMessageDialog(dialog, "订单中至少需要包含一个商品", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                
                // 获取选中的客户编号
                int selectedCustomerId = (int) customerIdComboBox.getSelectedItem();
                
                // 创建订单
                Order order = new Order(orderNumberField.getText(), selectedCustomerId);
                
                // 添加订单项
                for (int i = 0; i < orderItemsTableModel.getRowCount(); i++) {
                    int productId = (int) orderItemsTableModel.getValueAt(i, 0);
                    int quantity = (int) orderItemsTableModel.getValueAt(i, 3);
                    
                    // 查找对应的商品
                    for (Product product : parent.getProducts()) {
                        if (product.getId() == productId) {
                            order.addOrderItem(product, quantity);
                            break;
                        }
                    }
                }
                
                // 保存订单
                parent.addOrder(order);
                refreshTable();
                dialog.dispose();
                JOptionPane.showMessageDialog(parent, "订单创建成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        
        dialog.setVisible(true);
    }
    
    // 更新订单总金额
    private void updateTotalAmount(DefaultTableModel model, JTextField totalField) {
        double total = 0;
        for (int i = 0; i < model.getRowCount(); i++) {
            total += (double) model.getValueAt(i, 4);
        }
        totalField.setText(String.format("%.2f", total));
    }
    
    // 显示订单详情对话框
    private void showOrderDetailDialog() {
        int selectedRow = orderTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要查看的订单", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String orderNumber = (String) tableModel.getValueAt(selectedRow, 0);
        Order orderToView = null;
        
        for (Order order : parent.getOrders()) {
            if (order.getOrderNumber().equals(orderNumber)) {
                orderToView = order;
                break;
            }
        }
        
        if (orderToView == null) {
            JOptionPane.showMessageDialog(this, "未找到选中的订单", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        JDialog dialog = new JDialog((Frame) null, "订单详情 - " + orderNumber, true);
        dialog.setSize(600, 400);
        dialog.setLocationRelativeTo(null);
        dialog.setLayout(new BorderLayout());
        
        // 创建订单信息面板
        JPanel orderInfoPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        orderInfoPanel.setBorder(BorderFactory.createTitledBorder("订单信息"));
        
        JLabel orderNumberLabel = new JLabel("订单编号:");
        JTextField orderNumberField = new JTextField(orderToView.getOrderNumber());
        orderNumberField.setEditable(false);
        
        JLabel orderDateLabel = new JLabel("下单日期:");
        JTextField orderDateField = new JTextField(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderToView.getOrderDate()));
        orderDateField.setEditable(false);
        
        JLabel customerIdLabel = new JLabel("客户编号:");
        JTextField customerIdField = new JTextField(String.valueOf(orderToView.getCustomerId()));
        customerIdField.setEditable(false);
        
        JLabel totalAmountLabel = new JLabel("订单总金额:");
        JTextField totalAmountField = new JTextField(String.format("%.2f", orderToView.getTotalAmount()));
        totalAmountField.setEditable(false);
        totalAmountField.setBackground(Color.LIGHT_GRAY);
        
        orderInfoPanel.add(orderNumberLabel);
        orderInfoPanel.add(orderNumberField);
        orderInfoPanel.add(orderDateLabel);
        orderInfoPanel.add(orderDateField);
        orderInfoPanel.add(customerIdLabel);
        orderInfoPanel.add(customerIdField);
        orderInfoPanel.add(totalAmountLabel);
        orderInfoPanel.add(totalAmountField);
        
        // 创建订单商品表格
        String[] columnNames = {"商品编号", "商品名称", "单价", "数量", "小计"};
        DefaultTableModel orderItemsTableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        
        for (Order.OrderItem item : orderToView.getOrderItems()) {
            Product product = item.getProduct();
            Object[] rowData = {
                product.getId(),
                product.getName(),
                item.getUnitPrice(),
                item.getQuantity(),
                item.getSubtotal()
            };
            orderItemsTableModel.addRow(rowData);
        }
        
        JTable orderItemsTable = new JTable(orderItemsTableModel);
        
        JPanel orderItemsPanel = new JPanel(new BorderLayout());
        orderItemsPanel.setBorder(BorderFactory.createTitledBorder("订单商品"));
        orderItemsPanel.add(new JScrollPane(orderItemsTable), BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton closeButton = new JButton("关闭");
        buttonPanel.add(closeButton);
        
        // 添加到对话框
        dialog.add(orderInfoPanel, BorderLayout.NORTH);
        dialog.add(orderItemsPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 关闭按钮事件
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        
        dialog.setVisible(true);
    }
    
    // 删除选中的订单
    private void deleteSelectedOrder() {
        int selectedRow = orderTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的订单", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String orderNumber = (String) tableModel.getValueAt(selectedRow, 0);
        
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除订单" + orderNumber + "吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            parent.deleteOrder(orderNumber);
            refreshTable();
            JOptionPane.showMessageDialog(this, "订单删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    // 商品列表渲染器
    private class ProductListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof Product) {
                Product product = (Product) value;
                setText(product.getName() + " (编号: " + product.getId() + ", 单价: " + product.getUnitPrice() + ")");
            }
            return component;
        }
    }
}